package com.smart.web.service.impl;

import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.smart.common.base.exception.ServiceException;
import com.smart.common.base.result.ResultCode;
import com.smart.common.base.utils.CommonBeanUtils;
import com.smart.web.entity.CartItem;
import com.smart.web.mapper.CartItemMapper;
import com.smart.web.reqeust.CartRequestParams;
import com.smart.web.service.CartItemService;
import com.smart.web.vo.CartItemVo;
import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.List;

@Service
public class CartItemServiceImpl implements CartItemService {
    @Resource
    CartItemMapper cartItemMapper;

    //    qo---->po
    @Override
    public int save(CartRequestParams requestParams) {
        CartItem cartItem = new CartItem();
        BeanUtils.copyProperties(requestParams, cartItem);
        int count = cartItemMapper.insert(cartItem);
        return count;
    }


    @Override
    public int del(Long cartId) {
        int count = cartItemMapper.deleteById(cartId);
        return count;
    }

    /**
     * Page
     * CartItem-> CartItemVo
     *
     * @param memberId
     * @param page
     * @param size
     * @return
     */
    @Override
    public IPage<CartItemVo> list(Long memberId, Integer page, Integer size) {
        IPage<CartItem> cartItemIPage = cartItemMapper.selectListByMemberId(memberId, page, size);
        List<CartItem> cartItems = cartItemIPage.getRecords();
        // 数据转化
        IPage<CartItemVo> cartItemVoIPage = new Page<>();
        BeanUtils.copyProperties(cartItemIPage, cartItemIPage);
        List<CartItemVo> cartItemVos = CommonBeanUtils.copyListProperties(cartItems, CartItemVo::new);
        cartItemVoIPage.setRecords(cartItemVos);
        return cartItemVoIPage;
    }

    @Override
    public int batchDel(List<Long> ids) {
        int count = cartItemMapper.deleteBatchIds(ids);
        return count;
    }

    /**
     * @param cartId
     * @param quantity
     * @return
     */
    @Override
    public int modifyQuantity(Long cartId, Integer quantity) {
        int count = 0;
        CartItem cartItem = cartItemMapper.selectById(cartId);
        if (cartItem != null) {
            cartItem.setQuantity(quantity);
            count = cartItemMapper.updateById(cartItem);
        } else {
            throw new ServiceException(ResultCode.ERROR);
        }
        return count;
    }

}
